var db = openDatabase('diabetbook', 1, 'DB', 2 * 1024 * 1024);
var _LANG_ = _FR_;
//Navigation

$('a[href="#graph"]').click(function() {
    $('nav li').removeClass("active");
    $('nav li a[href="#graph"]').parent().addClass("active");
    window.history.forward(1);
	graf();
});
$('a[href="#table"]').click(function() {
	$('#wrapper').css("width","auto");
    $('nav li').removeClass("active");
    $('nav li a[href="#table"]').parent().addClass("active");
	draw();
});
$('a[href="#list"]').click(function() {
	$('#wrapper').css("width","auto");
    $('nav li').removeClass("active");
    $('nav li a[href="#list"]').parent().addClass("active");
});
$('a[href="#dextro"]').click(function() {
	$('#wrapper').css("width","auto");
	var d = new Date();
	$('.dateNow').val(ISODateString(d));
    $('nav li').removeClass("active");
    $('nav li a[href="#dextro"]').parent().addClass("active");
});
$('a[href="#home"]').click(function() {
	$('#wrapper').css("width","auto");
    $('nav li').removeClass("active");
    $('nav li a[href="#home"]').parent().addClass("active");
});
$('a[href="#inscription"]').click(function() {
    $('nav li').removeClass("active");
    //$('#insc_login').attr('autofocus', 'autofocus');
});
$('a[href="#forget"]').click(function() {
    $('nav li').removeClass("active");
});

//Chargement

$(window).load(
function()
{
	if(localStorage.getItem("mylogin") != null){
		autoconnect(localStorage.getItem("mylogin"), localStorage.getItem("mypass"), localStorage.getItem("myremember"), "1");
	}else{
		$("#home_ko").show(); 
	}
	var db = openDatabase('diabetbook', 1, 'DB', 2 * 1024 * 1024);
	db.transaction(function (tx) {
  		tx.executeSql('CREATE TABLE IF NOT EXISTS data (id, date, value, type)');
  		tx.executeSql('CREATE TABLE IF NOT EXISTS dextro (id, date, value)');
  		tx.executeSql('CREATE TABLE IF NOT EXISTS insulin (id, date, value, type)');
  		tx.executeSql('CREATE TABLE IF NOT EXISTS com (id, date, value)');

	});
	loadlist();
	loadlang()
}
);

function loadlang(){
	//home
	$('.txt_connection').value = _LANG_.txtConnection;
	$('.txt_emaillogin').attr('placeholder', _LANG_.txtEmailLogin);
	$('.txt_password').attr('placeholder', _LANG_.txtMotDePasse);
	$('.txt_inscription').html(_LANG_.txtInscription);
	$('.txt_forgotten').html(_LANG_.txtPassOublie);
	$('.txt_remember').html(_LANG_.txtSeSouvenir);
	$('.txt_settings').html(_LANG_.txtParametres);
	$('.txt_logout').html(_LANG_.txtDeco);
	$('.txt_submit').value = _LANG_.txtEnvoye;
	$('.txt_cancel').html(_LANG_.txtAnnule);
	$('.txt_email').attr('placeholder',_LANG_.txtEmail);
	$('.txt_login').attr('placeholder',_LANG_.txtLogin);
	$('.txt_confirmpassword').attr('placeholder',_LANG_.txtConfirmPass);
	$('.txt_return').html(_LANG_.txtRetour);
	//add
	$('.txt_dextro').html(_LANG_.txtDextro);
	$('.txt_insulin').html(_LANG_.txtInsuline);
	$('.txt_comment').html(_LANG_.txtCom);
	$('.txt_dextrovalue').attr('placeholder',_LANG_.txtValeurDextro);
	$('.txt_insulinunits').attr('placeholder',_LANG_.txtUniteInsuline);
	$('.txt_yourcomment').attr('placeholder',_LANG_.txtVotreCom);
	//list
	$('.txt_loaddata').html(_LANG_.txtChargementDonnees);
}

// Connection
$("body").keypress(function(event) {
	if ( event.which == 13 && $('nav li a[href="#home"]').parent().hasClass("active")) {
     	connect();
	}
	if ( event.which == 13 && window.location.hash.substring(1) == "forget") {
     	btn_forgetPass();
	}
	if ( event.which == 13 && window.location.hash.substring(1) == "inscription") {
     	btn_inscription();
	}
});

function connect() {
		var login = document.forms["connection"].login.value;
		var pass = document.forms["connection"].pass.value;
		if(pass == "" || login == ""){
			$('.alerte').html(_LANG_.errChampsManquant);
			$('.alerte').css("display","block");
			$('.alerte').delay(2000).hide(200);
		}else{
			var remember = document.forms["connection"].remember.checked;
			var iscrypt = "0";
			autoconnect(login, pass, remember, iscrypt);
		}
}

function autoconnect(mylogin, mypass, myremember, iscrypt){
	var alerte;
	$.post("connect.php", { login: mylogin, pass: mypass, iscrypt: iscrypt},
	   function(data){
		 if(data=="-1"){
			alerte = _LANG_.errConnectionServeur;
		 }else if(data=="0" || data == "-2"){
		 	alerte = _LANG_.errLoginPasswordIncorrect;
	   	} else {
			//connection ok
			var elem = data.split(' ');
			myid = elem[1];
			pass = elem[0];
			sessionStorage.setItem("mylogin", mylogin);
			sessionStorage.setItem("mypass", pass);
			if(myremember){
				localStorage.setItem("mylogin", mylogin);
				localStorage.setItem("mypass", pass);
				localStorage.setItem("myremember", myremember);
			}
			alerte = "";
		 }
		 affichageformulaire(alerte);
	});
}

function affichageformulaire(alerte){
	if(sessionStorage.getItem("mypass")){
		$("#home_ko").hide(); 
		$("#home_ok").show();
		$('.welcome').html(_LANG_.txtBienvenue+" "+sessionStorage.getItem("mylogin"));
	}else{
		$("#home_ko").show(); 
		$("#home_ok").hide(); 
		document.forms["connection"].pass.value = "";
		if (localStorage.getItem("myremember")) 
		{ 
			//document.forms["connection"].elements["login"].value = localStorage.getItem("mylogin");
			document.forms["connection"].elements["login"].focus();
			document.forms["connection"].elements["remember"].checked = true;
		}
		$('.alerte').html(alerte);
		$('.alerte').css("display","block");
		$('.alerte').delay(2000).hide(200);
	}
}
function isconnect() {
	$.ajax({
	  type: "POST",
	  url: "isconnect.php",
	  async: false,
	  data: { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass") }
	}).done(function( data ) {
	  ret = data;
		//alert(sessionStorage.getItem("mylogin")+ret);
		//return ret;

	});
	/*$.post("isconnect.php", { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass") },
	function(data){
		ret = data;
		
		return ret;
	});*/
	//alert(sessionStorage.getItem("mylogin")+ret);
	return ret;
}

function deco(){
	localStorage.clear();
	sessionStorage.clear();
	affichageformulaire("");
}

function recupbdd(){
	//récupération via requete PHP
	$.post("synchro.php", { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass") },
	function(data){
		return data;
	});
	//découpage du resultat php dans tableau ?
	
	//si l'id de la BDD n'existe pas en local on le copie
	
	//si il y a des enregistrement locaux non attribués, on les compare avec ceux de la BDD, 
		//si ils sont égaux ont attribus l'id BDD au local
		//sinon on upload la valeur avec un nouvel id
	
	
}
//LIST
function loadlist(multi){
	var form="";
	if(!multi){
		var multi = 1;
	}
	var limit = 10*multi;
	db.transaction(function (tx) {
		tx.executeSql("SELECT id, date, value, 'com' AS type from com UNION SELECT id, date, value, 'dextro' AS type FROM dextro UNION SELECT id, date, value, type from insulin order by date DESC LIMIT ?",[limit+1],function(tx, rs) {
			var jour="";
			if(limit+1 == rs.rows.length){
				$('a.list_load').css("display","block");
				$('a.list_load').attr("multi",parseInt(multi)+1);
			}else{
				$('a.list_load').css("display","none");
			}
			for(var i=0; i < rs.rows.length-1; i++) {
				
	          	r = rs.rows.item(i);
	          	madate = new Date(r['date']);
	          	newjour = madate.getDate()+"-"+madate.getMonth()+"-"+madate.getFullYear();
	          	if(jour != newjour){
	          		form += '<li class="day">'+_LANG_.jourSemaine[madate.getDay()]+' '+madate.getDate()+' '+_LANG_.jourMois[madate.getMonth()]+'</li>';
	          		jour = newjour;
	          	}
	          	var monHeure = madate.getHours();
	          	var mesMinutes = madate.getMinutes();
	          	if(monHeure<10){
	          		monHeure = "0"+monHeure;
	          	}
	          	if(mesMinutes<10){
	          		mesMinutes = "0"+mesMinutes;
	          	}
	          	if(r['type'] == "dextro"){
	          		form += '<li><span>'+monHeure+'h'+mesMinutes+' : '+r['value']+' mg/dl</span><a href="#list" class="delete" onclick="deleteValue()">Delete</a><a href="#list" class="update" onclick="updateValue()">Update</a></li>';
	          	}else if(r['type'] == "com"){
	          		form += '<li><span>'+monHeure+'h'+mesMinutes+' : '+r['value']+'</span><a href="#list" class="delete" onclick="deleteValue()">Delete</a><a href="#list" class="update" onclick="updateValue()">Update</a></li>';
	          	}else{
	          		form += '<li><span>'+monHeure+'h'+mesMinutes+' : '+r['value']+' U</span><a href="#list" class="delete" onclick="deleteValue()">Delete</a><a href="#list" class="update" onclick="updateValue()">Update</a></li>';
	       		}
	        }
	        $('#list ul').html(form);
	    });
	});
}
function deleteValue(id) {
    confirm(_LANG_.verifSuppressionValeur);
}
function updateValue(id) {
	if(!$(this).parent().hasClass('up')){
		$('#list li').removeClass('up');
		$('#list form').remove();
    	$(this).parent().addClass('up');
		var form = '<form class="form1"><input type="datetime" value="2012-03-16T11:35:00Z"><input type="number" value="100"><input type="button" value="Upload"></form>';
	 	$(this).parent().append(form);
	}else{
		$('#list li').removeClass('up');
		$('#list form').remove();
	}
}
$('a.list_load').click(function() {
	loadlist($(this).attr("multi"));
});
//TABLE
$(window).bind("resize", function(){
    draw(); 
	//graf();
});
function draw() {  
		 var nbr_ligne = 30;
		 var marge_x = 40;
      var canvas = document.getElementById("line");  
	  canvas.width = document.width;
      if (canvas.getContext) {  
        var ctx = canvas.getContext("2d");  
		ctx.lineWidth = 1; 
		ctx.beginPath();
		var coef_y;
		if(canvas.width >= 1000){ coef_y = 1;}
		else if(canvas.width >= 500){coef_y = 2;}
		else if(canvas.width >= 250){coef_y = 4;}
		for(var i=marge_x; i<= canvas.width; i+= (canvas.width-marge_x)/24*coef_y){
			var h = Math.round((i-marge_x)/((canvas.width-marge_x)/24));
			ctx.font = "12pt Helvetica,Arial";
			ctx.fillText(h+"h", i, 20);
			ctx.moveTo(i,30);  
			ctx.lineTo(i,50); 
		}  
		ctx.stroke(); 
	    }  
		
		var canvas2 = document.getElementById("line2");  
	  canvas2.width = document.width;
	  canvas2.height = nbr_ligne*20;;
      if (canvas2.getContext) {  
        var ctx = canvas2.getContext("2d");   
		ctx.lineWidth = 1;
		ctx.strokeStyle = "#888888";
		ctx.beginPath();
		var coef_y;
		var marge_x = 40;
		if(canvas.width >= 1000){ coef_y = 1;}
		else if(canvas.width >= 500){coef_y = 2;}
		else if(canvas.width >= 250){coef_y = 4;}
		for(var i=marge_x; i<= canvas2.width; i+= (canvas2.width-marge_x)/24*coef_y){
			ctx.moveTo(i,0);  
			ctx.lineTo(i,canvas2.height); 
		}  
		ctx.stroke(); 
		for( var i=0; i<= nbr_ligne ; i++){
			ctx.font = "12pt Helvetica,Arial";
			ctx.fillText(i+1, 10, i*20+20);
			var heure=12;
			var minute=35;
			var temps=heure*60+minute;
			ctx.fillText("test", marge_x+(temps*(canvas2.width-marge_x)/1440), i*20+20);
		}
		ctx.stroke();  
	  }  
	  
}
function graf() { 
	$('#wrapper').css("width","5000");
	  var canvas3 = document.getElementById("graf");  
	  canvas3.height = document.height - 43;
	  canvas3.width = 5000;
	  $('html, body').animate({scrollLeft:$(document).width()}, 'slow');
      if (canvas3.getContext) {  
        var ctx = canvas3.getContext("2d");  
		ctx.beginPath();
		ctx.moveTo(25,25);
		ctx.lineTo(4505,25);
		ctx.lineTo(25,305);
		ctx.fill();
		
	    }  
    } 

function ISODateString(d){
	function pad(n){return n<10 ? '0'+n : n}
	return d.getUTCFullYear()+'-'
      + pad(d.getUTCMonth()+1)+'-'
      + pad(d.getUTCDate())+'T'
      + pad(d.getUTCHours())+':'
      + pad(d.getUTCMinutes())+':'
      + pad(d.getUTCSeconds())+'Z'
}

function btn_forgetPass(){
	var email = document.forms["forget"].forget_email.value;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var alerte = "";
	if(email == "") {
		alerte =_LANG_.errChampManquant;
    }else if(!emailReg.test(email)){
    	alerte =_LANG_.errEmailIncorrect;
	}else{
		$.post("forget.php", {email: email },
			function(data){
			 if(data=="-1"){
				alerte = _LANG_.errConnectionServeur;
			 }else if(data=="0"){
			 	alerte = _LANG_.errEmailInconnu;
		   	} else {
				//connection ok
			
				alerte = _LANG_.validEnvoiPass;
				$('.alerte_mail').css("color","green");
			 }
		});
	}
	$('.alerte_mail').html(alerte);
	$('.alerte_mail').css("display","block");
	$('.alerte_mail').delay(2000).hide(200);
}

function btn_inscription(){
	var login = document.forms["inscription"].insc_login.value;
	var email = document.forms["inscription"].insc_email.value;
	var pass = document.forms["inscription"].insc_password.value;
	var pass2 = document.forms["inscription"].insc_password2.value;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var alerte = "";
	if(login == "" || email == "" || pass == "" || pass2 == "") {
		alerte =_LANG_.errChampsManquant;
    }else if(!emailReg.test(email)){
		alerte =_LANG_.errEmailIncorrect;
	}else if(pass != pass2){
		alerte = _LANG_.errMdpDifferent;
	}else if(pass.length <6){
		alerte = _LANG_.errMdpCourt;
	}else{
		$.post("inscription.php", { login: login, pass: pass, email: email },
		   function(data){
			 if(data=="-1"){
				alerte = _LANG_.errConnectionServeur;
			 }else if(data=="0"){
			 	alerte = _LANG_.errLoginEmailUtilise;
		   	} else {
				//connection ok
			
				alerte = data;
			 }
		});
	}
	$('.alerte_insc').html(alerte);
	$('.alerte_insc').css("display","block");
	$('.alerte_insc').delay(2000).hide(200);
}
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
function addDextro(){
	var madate = document.forms["dextro"].dextro_date.value;
	var val = document.forms["dextro"].dextro_value.value;
	var alerte = "";
	if(val == "" || madate == ""){
		alerte=_LANG_.errChampsManquant;
	}else if(val != parseInt(val)) {
        alerte=_LANG_.errValeurNombre;
	}else{
		if(isconnect() == "1"){
			alert("envoi vers bdd");
			//script php
			$.post("adddextro.php", { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass"), date: madate, value: val },
		   function(data){
				 if(data=="-1"){
				 	alert("erreur serveur");
					alerte = _LANG_.errConnectionServeur;
				 }else if(data=="0"){
				 	alert("erreur id");
				 	alerte = _LANG_.errLoginEmailUtilise;
			   	} else {
			   		
			   		alert(data+", "+madate+", "+val);
					//connection ok
					db.transaction(function (tx) {
						tx.executeSql('INSERT INTO dextro (id, date, value) VALUES (?,?,?)', [data, madate, val]);
			        	document.forms["dextro"].dextro_value.value = "";
			        	loadlist();
			    	});
				alerte=_LANG_.validDonneesAjout;
				 }
			});
		}else{
		
			db.transaction(function (tx) {
				tx.executeSql("SELECT MIN(id) AS minid FROM data",[],function(tx, rs) {
					var idmin;
			        if (!rs.rows.length) {
			            idmin = 0;
			        }else {
			            var row = rs.rows.item(0);
			            idmin = row['minid'] - 1;
			        }
			        //tx.executeSql('INSERT INTO data (id, date, value, type) VALUES (?,?,?,?)', [idmin,madate,val,'dextro']);
			        tx.executeSql('INSERT INTO dextro (id, date, value) VALUES (?,?,?)', [idmin,madate,val]);
			        document.forms["dextro"].dextro_value.value = "";
			        loadlist();
			    });
			});
			alerte=_LANG_.validDonneesAjoutLocal;
		}
	}
	$('.alerte_dextro').html(alerte);
	$('.alerte_dextro').css("display","block");
	$('.alerte_dextro').delay(2000).hide(200);
}
function addInsulin(){
	var madate = document.forms["insulin"].insulin_date.value;
	var val = document.forms["insulin"].insulin_value.value;
	var type = document.forms["insulin"].insulin_type.value;
	var alerte = "";
	if(val == "" || madate == ""){
		alerte=_LANG_.errChampsManquant;
	}else if(val != parseInt(val)) {
        alerte=_LANG_.errValeurNombre;
	}else{
		if(isconnect() == "1"){
			alert("envoi vers bdd");
			//script php
			$.post("addinsulin.php", { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass"), date: madate, value: val, type:type },
		   function(data){
				 if(data=="-1"){
				 	alert("erreur serveur");
					alerte = _LANG_.errConnectionServeur;
				 }else if(data=="0"){
				 	alert("erreur id");
				 	alerte = _LANG_.errLoginEmailUtilise;
			   	} else {
			   		
			   		alert(data+", "+madate+", "+val+", "+type);
					//connection ok
					db.transaction(function (tx) {
						tx.executeSql('INSERT INTO insulin (id, date, value, type) VALUES (?,?,?,?)', [data, madate, val, type]);
			        	document.forms["insulin"].insulin_value.value = "";
			        	loadlist();
			    	});
				alerte=_LANG_.validDonneesAjout;
				 }
			});
		}else{
		
			db.transaction(function (tx) {
				tx.executeSql("SELECT MIN(id) AS minid FROM insulin",[],function(tx, rs) {
					var idmin;
			        if (!rs.rows.length) {
			            idmin = 0;
			        }else {
			            var row = rs.rows.item(0);
			            idmin = row['minid'] - 1;
			        }
			        tx.executeSql('INSERT INTO insulin (id, date, value, type) VALUES (?,?,?,?)', [idmin, madate, val, type]);
			        document.forms["insulin"].insulin_value.value = "";
			        loadlist();
			    });
			});
			alerte=_LANG_.validDonneesAjoutLocal;
		}
	}
	$('.alerte_insulin').html(alerte);
	$('.alerte_insulin').css("display","block");
	$('.alerte_insulin').delay(2000).hide(200);
}
function addCom(){
	var madate = document.forms["com"].com_date.value;
	var txt = document.forms["com"].com_txt.value;
	var alerte = "";
	if(txt == "" || madate == ""){
		alerte=_LANG_.errChampsManquant;
	}else{
		if(isconnect() == "1"){
			alert("envoi vers bdd");
			//script php
			$.post("addcom.php", { login: sessionStorage.getItem("mylogin"), pass: sessionStorage.getItem("mypass"), date: madate, txt: txt },
		   function(data){
				 if(data=="-1"){
					alerte = _LANG_.errConnectionServeur;
				 }else if(data=="0"){
				 	alerte = _LANG_.errLoginEmailUtilise;
			   	} else {
			   		
			   		alert(data+", "+madate+", "+val);
					//connection ok
					db.transaction(function (tx) {
						tx.executeSql('INSERT INTO com (id, date, value) VALUES (?,?,?)', [data, madate, txt]);
			        	document.forms["com"].com_txt.value = "";
			        	loadlist();
			    	});
				alerte=_LANG_.validDonneesAjout;
				 }
			});
		}else{
		
			db.transaction(function (tx) {
				tx.executeSql("SELECT MIN(id) AS minid FROM com",[],function(tx, rs) {
					var idmin;
			        if (!rs.rows.length) {
			            idmin = 0;
			        }else {
			            var row = rs.rows.item(0);
			            idmin = row['minid'] - 1;
			        }
			        tx.executeSql('INSERT INTO com (id, date, value) VALUES (?,?,?)', [idmin, madate, txt]);
			        document.forms["com"].com_txt.value = "";
			        loadlist();
			    });
			});
			alerte=_LANG_.validDonneesAjoutLocal;
		}
	}
	$('.alerte_com').html(alerte);
	$('.alerte_com').css("display","block");
	$('.alerte_com').delay(2000).hide(200);
}